package com.bw.common.mvvm.view;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;

import com.bw.common.entity.LiveDataEntity;
import com.bw.common.mvvm.viewmodel.BaseViewModel;

import java.lang.ref.WeakReference;
import java.lang.reflect.ParameterizedType;

public abstract class BaseFragment<V extends ViewBinding,VM extends BaseViewModel> extends Fragment implements IView{
    protected LayoutInflater inflater = null;
    protected V v;
    protected VM vm;
    private LiveDataFragment liveDataFragment = null;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        liveDataFragment = new LiveDataFragment(this);
        inflater = LayoutInflater.from(getContext());
        initViewModel();
        getLifecycle().addObserver(vm);
        v = (V) initBinding();
        vm.getLiveDataViewModel().getUiData().observe(this,liveDataFragment);
        initView();
        initData();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return bindLayout();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        vm.getLiveDataViewModel().getUiData().removeObserver(liveDataFragment);
        getLifecycle().removeObserver(vm);
    }

    @Override
    public void initViewModel() {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        Class clazz = (Class) type.getActualTypeArguments()[1];
        vm = (VM) new ViewModelProvider(this,new ViewModelProvider.NewInstanceFactory())
                .get(clazz);
    }

    public abstract void handleMessage(LiveDataEntity entity);


    public static class LiveDataFragment implements Observer<LiveDataEntity> {
        private WeakReference<BaseFragment> weakReference;

        public LiveDataFragment(BaseFragment fragment) {
            weakReference = new WeakReference<>(fragment);
        }

        @Override
        public void onChanged(LiveDataEntity liveDataEntity) {
            if (weakReference.get() == null||liveDataEntity == null || liveDataEntity.action == null){
                return;
            }
            weakReference.get().handleMessage(liveDataEntity);
        }
    }
}
